import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hm_show_flutter/api/service/user_service.dart';
import 'package:hm_show_flutter/config/routers.dart';
import 'package:hm_show_flutter/constant/string.dart';
import 'package:hm_show_flutter/entity/upload_avatar_entity.dart';
import 'package:hm_show_flutter/entity/user.dart';
import 'package:hm_show_flutter/entity/user_info_entity.dart';
import 'package:hm_show_flutter/event/login_event.dart';
import 'package:hm_show_flutter/event/user_update_event.dart';
import 'package:hm_show_flutter/style/style.dart';
import 'package:hm_show_flutter/utils/navigator_util.dart';
import 'package:hm_show_flutter/utils/permission_util.dart';
import 'package:hm_show_flutter/utils/shared_preferences_util.dart';
import 'package:hm_show_flutter/utils/toast_util.dart';
import 'package:hm_show_flutter/widgets/AppLoadingDialog.dart';
import 'package:hm_show_flutter/widgets/icon_text_arrow.dart';
import 'package:hm_show_flutter/widgets/icon_text_arrow_it.dart';
import 'package:hm_show_flutter/widgets/loading_dialog.dart';
import 'package:hm_show_flutter/widgets/mall_icon.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:image_picker/image_picker.dart';

///设置
class SettingPage extends StatefulWidget {
  @override
  _SettingPageState createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  UserService _userService = new UserService();
  UserModel _userModel;

  File imageFile;

  @override
  void initState() {
    super.initState();
    _getUserInfo();

    _registerEventBus();
  }

  void _registerEventBus() {
    userUpdateEventBus.on<UserUpdateEvent>().listen((event) {
      _getUserInfo();
    });
  }

  void _getUserInfo() {
    _userService.getUserInfo((success) {
      UserInfoEntity model = success;
      _userModel = model.data.user;
      SharedPreferencesUtils.saveUser(_userModel);
      setState(() {});
    });
  }

  _loginOutDialog() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text(
              Strings.TIPS,
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(30),
                  color: Colors.black54),
            ),
            content: Text(
              Strings.LOGIN_OUT_TIPS,
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(30),
                  color: Colors.black54),
            ),
            actions: <Widget>[
              FlatButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(
                  Strings.CANCEL,
                  style: TextStyle(color: Colors.black54),
                ),
              ),
              FlatButton(
                onPressed: () => _loginOut(),
                child: Text(
                  Strings.CONFIRM,
                  style: TextStyle(color: Colors.red),
                ),
              )
            ],
          );
        });
  }

  _loginOut() {
//    _userService.loginOut((success) {
//      Navigator.of(context).pushNamedAndRemoveUntil(
//          Routers.login, ModalRoute.withName(Routers.login));
//    }, (error) {
//      ToastUtil.showToast(error);
//    });
    loginOut();
  }

  Future loginOut() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    await sp.setString(Strings.token, null);
    await sp.setString(SharedPreferencesUtils.SP_COMPANY, null);
    await sp.setString(SharedPreferencesUtils.SP_USER, null);

    Navigator.of(context).pushNamedAndRemoveUntil(
        Routers.login, ModalRoute.withName(Routers.login));
  }

  @override
  Widget build(BuildContext context) {
    void _editName() {
      NavigatorUtils.goEditName(context);
    }

    void showUploadAvatar() {
      PermissionUtil.checkCameraStoragePermission().then((isGranted) {
        if (isGranted) {
          //有权限
          showModalBottomSheet(
              context: context,
              builder: (BuildContext context) {
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    GestureDetector(
                      child: Container(
                          color: Colors.white,
                          alignment: Alignment.center,
                          padding: EdgeInsets.all(10),
                          child: Text("拍照")),
                      onTap: () async {
                        Navigator.pop(context);
                        imageFile = await ImagePicker.pickImage(
                            source: ImageSource.camera);
                        await _avatarCropUpload();
                      },
                    ),
                    GestureDetector(
                      child: Container(
                          color: Colors.white,
                          alignment: Alignment.center,
                          padding: EdgeInsets.all(10),
                          child: Text("相册")),
                      onTap: () async {
                        Navigator.pop(context);
                        imageFile = await ImagePicker.pickImage(
                            source: ImageSource.gallery);
                        await _avatarCropUpload();
                      },
                    ),
                    Container(
                      color: Colors.grey[100],
                      height: 8,
                    ),
                    GestureDetector(
                      child: Container(
                          color: Colors.white,
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(top: 8, bottom: 8),
                          child: Text("取消")),
                      onTap: () {
                        Navigator.pop(context);
                      },
                    ),
                  ],
                );
              });
        }
      });
    }

    final loginButton = Container(
      width: double.infinity,
      padding: EdgeInsets.all(16),
      child: RaisedButton(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5),
        ),
        onPressed: _loginOutDialog,
        padding: EdgeInsets.all(12),
        color: Colors.red,
        child: Text(Strings.LOGIN_OUT,
            style: TextStyle(
              color: Colors.white,
            )),
      ),
    );

    return Scaffold(
      appBar: PreferredSize(
        child: AppBar(
          automaticallyImplyLeading: true,
          centerTitle: true,
          iconTheme: IconThemeData(color: Colors.white),
          title: Text(
            "个人设置",
            style: TextStyle(color: Colors.white, fontSize: 18),
          ),
          backgroundColor: AppColors.mainColor,
        ),
        preferredSize: Size.fromHeight(40),
      ),
      body: _userModel == null
          ? LoadingDialog()
          : Container(
              color: Colors.grey[100],
              child: Column(
                children: <Widget>[
                  IconTextArrowITView(
                    "我的头像",
                    Colors.deepPurpleAccent,
                    showUploadAvatar,
                    rightIcon: _userModel.url,
                  ),
                  Divider(
                    height: ScreenUtil.getInstance().setHeight(1.0),
                    color: Color(0xffd3d3d3),
                    endIndent: 20,
                    indent: 10,
                  ),
                  IconTextArrowITView(
                    "用户名称",
                    Colors.amber,
                    _editName,
                    rightText: _userModel.name,
                  ),
                  Expanded(child: Container()),
                  loginButton
                ],
              ),
            ),
    );
  }

  Future _avatarCropUpload() async {
    if (imageFile == null) {
      return;
    }
    File croppedFile = await ImageCropper.cropImage(
        sourcePath: imageFile.path,
        aspectRatioPresets: [
          CropAspectRatioPreset.square,
        ],
        androidUiSettings: AndroidUiSettings(
            toolbarTitle: '裁剪图片',
            toolbarColor: Colors.deepOrange,
            toolbarWidgetColor: Colors.white,
            initAspectRatio: CropAspectRatioPreset.original,
            lockAspectRatio: false),
        iosUiSettings: IOSUiSettings(
          minimumAspectRatio: 1.0,
        ));

    if (croppedFile == null) {
      return;
    }
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AppLoadingDialog(
            text: "上传中...",
          );
        });

    _userService.uploadAvatar(croppedFile, (success) {
      UploadAvatarEntity entity = success;
      UploadAvatarData data = entity.data;
      if (data != null) {
        _userService.updateUserInfo(
            (success) {
              ToastUtil.showToast("上传成功");
              userUpdateEventBus.fire(UserUpdateEvent());
              Navigator.pop(context);
            },
            url: data.url,
            onFail: (onFail) {
              ToastUtil.showToast("更新失败");
              Navigator.pop(context);
            });
      }
    }, onFail: (onFail) {
      ToastUtil.showToast("上传失败");
      Navigator.pop(context);
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (imageFile != null) {
      imageFile.delete();
      imageFile = null;
    }
  }
}
